package com.lhh.company.website.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lhh.company.website.config.SysUserDetails;
import com.lhh.company.website.entity.Res;
import com.lhh.company.website.entity.SysException;
import com.lhh.company.website.entity.SysFile;
import com.lhh.company.website.mapper.SysFileMapper;
import com.lhh.company.website.utils.SysUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;

/**
* @author lx
* @description 针对表【sys_file(系统文件表)】的数据库操作Service实现
* @createDate 2025-07-23 15:50:31
*/
@Service
public class SysFileService extends ServiceImpl<SysFileMapper, SysFile> {

    @Value("${filepath}")
    String filepath;

    /**
     * 文件上传
     * @param file
     *
     * @param fileName
     * @throws IOException
     */
    @Transactional(rollbackFor = RuntimeException.class)
    public void fileUpload(String fileId , MultipartFile file, String fileName, SysUserDetails userDetails) throws IOException, SysException {

        if (file==null || file.isEmpty()) {
            throw new SysException("上传文件为空");
        }

        // 确保上传目录存在
        Path uploadPath = Paths.get(filepath);
        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }

        String originalFilename = file.getOriginalFilename();

        //  文件类型
        String fileType = originalFilename.substring(originalFilename.lastIndexOf(".")+1);


        SysFile sysFIle  = new SysFile();
        sysFIle.setId(fileId);
        sysFIle.setFileType(fileType);
        sysFIle.setName(fileName);
        sysFIle.setFileUrl("/static/"+ fileId+ "."+fileType);
        sysFIle.setCreatorid(userDetails.getId());
        sysFIle.setCreatorname(userDetails.getUsername());
        this.save(sysFIle);
        // 保存文件
        String targetFilePath = filepath+ fileId+ "."+fileType;
        File targetFile = new File(targetFilePath);
        Files.copy(file.getInputStream(), targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
    }



    public SysFile fileUploadToTmp(String fileId , MultipartFile file, String fileName) throws IOException, SysException {

        String filetmpPath = filepath+ "tmp/";

        if (file==null || file.isEmpty()) {
            throw new SysException("上传文件为空");
        }

        // 确保上传目录存在
        Path uploadPath = Paths.get(filetmpPath);
        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }

        String originalFilename = file.getOriginalFilename();

        //  文件类型
        String fileType = originalFilename.substring(originalFilename.lastIndexOf(".")+1);


        SysFile sysFIle  = new SysFile();
        sysFIle.setId(fileId);
        sysFIle.setFileType(fileType);
        sysFIle.setName(fileName);
        sysFIle.setFileUrl("/static/"+ fileId+ "."+fileType);
        // 保存文件
        String targetFilePath = filetmpPath+ fileId+ "."+fileType;
        File targetFile = new File(targetFilePath);
        Files.copy(file.getInputStream(), targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
        return sysFIle;
    }


    /**
     * 文件删除
     * @param id
     * @throws IOException
     */
    public void delete(String id) throws IOException {
        try{
            SysFile sysFIle = this.getById(id);
            Files.delete(Paths.get(filepath+id+"."+sysFIle.getFileType()));
            this.removeById(id);
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
    }
}




